#include "painter.h"
#include "ui_painter.h"

const int RectX = 40;
const int RectY = 40;

Painter::Painter(Tree *tree, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Painter)
{
    ui->setupUi(this);

    this->tree = tree;
}

Painter::~Painter()
{
    delete ui;
    delete tree;
}

void Painter::paintEvent(QPaintEvent *event) {
    QPainter painter(this);
    painter.setPen(QPen(Qt::black,5));
    QFont font;
    font.setPixelSize(28);
    painter.setFont(font);
    int height = tree->GetDepth();
    Queue<Pair<TreeNode*, Pair<int, int>>> que;
    que.Push(MakePair(tree->root, MakePair((1 << (height - 1)) * RectX, RectY)));
    while (!que.IsEmpty()) {
        auto v = que.Front();
        que.Pop();
        painter.drawArc(QRectF(v.second.first, v.second.second, RectX, RectY), 0, 360 * 16);
        painter.drawText(QRectF(v.second.first, v.second.second, RectX, RectY), Qt::AlignCenter, QString(v.first->val));
        int h = v.second.second / RectY / 2 + 1;
        if (v.first->lrchild.first != nullptr) {
            QLineF line(v.second.first + RectX / 2, v.second.second + RectY, v.second.first - RectX * ((1<<(height - h)) / 2) + RectX / 2, v.second.second + 2 * RectY);
            painter.drawLine(line);
            que.Push(MakePair(v.first->lrchild.first, MakePair(v.second.first - RectX * ((1<<(height - h)) / 2), v.second.second + 2 * RectY)));
        }
        if (v.first->lrchild.second != nullptr) {
            QLineF line(v.second.first + RectX / 2, v.second.second + RectY, v.second.first + RectX * ((1<<(height - h)) / 2) + RectX / 2, v.second.second + 2 * RectY);
            painter.drawLine(line);
            que.Push(MakePair(v.first->lrchild.second, MakePair(v.second.first + RectX * ((1<<(height - h)) / 2), v.second.second + 2 * RectY)));
        }
    }
}
